package com.whfp.coky.utils

import android.content.Context
import android.util.Log
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.whfp.coky.App
import com.whfp.coky.action.HandlerAction
import com.whfp.coky.event.EventCode
import com.whfp.coky.event.EventMessage

/**
 *
 * 定位工具
 * created by coky on 2022/4/2
 */
class LocationTool(val context: Context) :AMapLocationListener,HandlerAction{

    private var mLocationClient : AMapLocationClient? = null//定位发起端

    private var isLoced = false

    init{
       startLoc()
   }


    private fun startLoc(){
        if (mLocationClient == null){
            //初始化定位
            AMapLocationClient.updatePrivacyShow(context.applicationContext, true, true)
            AMapLocationClient.updatePrivacyAgree(context.applicationContext, true)
            mLocationClient = AMapLocationClient(context.applicationContext).apply {

                this.setLocationListener(this@LocationTool)
                this.setLocationOption(getLocOptions())
            }
        }
    }

    open fun getLocOptions():AMapLocationClientOption{
        return AMapLocationClientOption().apply {
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            this.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            //设置是否返回地址信息（默认返回地址信息）
            this.isNeedAddress = true
            //设置是否只定位一次,默认为false
            this.isOnceLocation = false
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            this.isMockEnable = false
            //设置定位间隔,单位毫秒,默认为2000ms
//            this.interval=2000
            //获取最近3s内精度最高的一次定位结果：
            //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
            this.isOnceLocationLatest = true
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            this.httpTimeOut = 20000
            //关闭缓存机制
            this.isLocationCacheEnable = false
        }
    }


    fun doLoc(){//开始定位
        LogUtil.e("location start...")
        mLocationClient?.let {
            if (!it.isStarted){
                it.startLocation()
                postDelayed({
                            if (!isLoced){
                                LogUtil.e("location failed...")
                                restartLoc()
                            }
                },5000L)
            }
        }
    }

    private fun restartLoc() {
        LogUtil.e("location restartLoc...")
        stopLocation()
        startLoc()
    }


    fun stopLocation(){//停止
        mLocationClient?.stopLocation()
    }

    fun destroyClient(){//销毁
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mLocationClient!!.onDestroy()
    }

    override fun onLocationChanged(mAMapLocation: AMapLocation?) {
        mAMapLocation?.let {
            when(it.errorCode){
                0->onLocDone(mAMapLocation)
                else ->  Log.e("AmapError","location Error, ErrCode:"
                        + mAMapLocation.errorCode + ", errInfo:"
                        + mAMapLocation.errorInfo)

            }
        }
    }


    private fun onLocDone(mAMapLocation: AMapLocation) {
        LogUtil.e("onLocDone---->lat:${mAMapLocation.latitude},lng:${mAMapLocation.longitude}")
        isLoced = true
        stopLocation()
        App.post(EventMessage(code = EventCode.LOCATION, obj = mAMapLocation))
    }

}